package com.qianfeng.service.impl;

import com.qianfeng.Event.CategoryChangeEvent;
import com.qianfeng.cache.CategoryCache;
import com.qianfeng.exception.AddDataException;
import com.qianfeng.exception.FindDataException;
import com.qianfeng.mapper.CategoryMapper;
import com.qianfeng.mapper.DeviceMapper;
import com.qianfeng.pojo.BaseUser;
import com.qianfeng.pojo.SysCategory;
import com.qianfeng.pojo.SysDevice;
import com.qianfeng.pojo.SysUserInfo;
import com.qianfeng.service.CategoryService;
import com.qianfeng.service.DeviceService;
import com.qianfeng.status.ResultCode;
import com.qianfeng.utils.LoginUsersUtils;
import com.qianfeng.utils.MyStringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.Assert;

import java.util.List;

/*
 *@Description:
 *@author:刘哥
 *@Date:86180 2022/9/6 19:21
 */
@Service
@Transactional

public class CategoryServiceImpl implements CategoryService {
    private CategoryCache categoryCache;

    @Autowired
    public void setCategoryCache(CategoryCache categoryCache) {
        this.categoryCache = categoryCache;
    }

    private ApplicationContext context;

    @Autowired
    public void setContext(ApplicationContext context) {
        this.context = context;
    }

    private DeviceService deviceService;

    @Autowired
    public void setDeviceMapper(DeviceService deviceService) {
        this.deviceService = deviceService;
    }

    private CategoryMapper categoryMapper;

    @Autowired
    public void setCategoryMapper(CategoryMapper categoryMapper) {
        this.categoryMapper = categoryMapper;
    }

    @Override
    public void addCategory(SysCategory sysCategory) {
        //设置创建者为当前登录用户,我们的登录用户的数据在session中保存着,我们可以从session中获取
        BaseUser loginUser = LoginUsersUtils.getLoginUser();
        Assert.isTrue(loginUser != null, () -> {
            throw new FindDataException("没有查询到用户,请先登录", ResultCode.Not_LOGIN_USERS_Not);
        });
        sysCategory.setCreateBy(loginUser.getUsername());

//        添加分类之前查询一下该分类是否存在
        SysCategory category = categoryMapper.findByCategoryName(sysCategory.getCategoryName());

//        Assert.isTrue(category == null && category.getStatus() != 1, () -> {
//            throw new AddDataException("分类已经存在,请重新添加", ResultCode.DATA_ALREADY_EXIST);
//        });
        if(category != null && category.getStatus() == 1){
            throw new AddDataException("分类已经存在,请重新添加", ResultCode.DATA_ALREADY_EXIST);
        }else if (category != null && category.getStatus() == 0) {
            category.setCategoryName(sysCategory.getCategoryName() + "&" + MyStringUtils.createRandomString(5));
            boolean b = true;
            while (b) {
                List<SysCategory> categoryList = categoryCache.getCategoryList();
                b = categoryList.stream()
                        .anyMatch(c -> c.getCategoryName().equals(category.getCategoryName()));
                category.setCategoryName(sysCategory.getCategoryName() +"&"+ MyStringUtils.createRandomString(5));
            }
        //        判断该分类是否被删除，
//        Assert.isTrue(category.getStatus()!=0,()->{
//            category.setCategoryName(sysCategory.getCategoryName()+"&"+ MyStringUtils.createRandomString(5));
//            category.setUpdateBy(loginUser.getName());
//            categoryMapper.updateCategory(category);
//            return null;
//        });

            category.setUpdateBy(loginUser.getUsername());
            categoryMapper.updateCategory(category);
        }

        categoryMapper.addCategory(sysCategory);
        context.publishEvent(new CategoryChangeEvent());
    }

    @Override
    public List<SysCategory> findAllCategoris() {
        List<SysCategory> categoryList = categoryCache.getCategoryList();
        Assert.isTrue(categoryList!=null,()->{
            throw new FindDataException("分类不存在",ResultCode.DATA_NOT_EXIST);
        });
        return categoryList;
    }

    @Override
    public SysCategory findById(Long cId) {
        SysCategory category = categoryCache.get(cId);
        Assert.notNull(category,()->{
            throw new FindDataException("该分类不存在",ResultCode.DATA_NOT_EXIST);
        });
        return category;
    }


    @Override
    public void updateCategory(SysCategory category) {
        BaseUser loginUser = LoginUsersUtils.getLoginUser();
        SysCategory categoryName = categoryMapper.findByCategoryName(category.getCategoryName());
        Assert.isTrue(categoryName==null,()->{
            throw new FindDataException("分类已存在,请重新修改", ResultCode.DATA_ALREADY_EXIST);
        });

        category.setUpdateBy(loginUser.getUsername());
        categoryMapper.updateCategory(category);
        context.publishEvent(new CategoryChangeEvent());
    }

    @Override
    public void deleteById(Long cId) {
        SysCategory category = categoryCache.get(cId);
        Assert.isTrue(category!=null,()->{
            throw new FindDataException("该分类不存在,请重新操作",ResultCode.DATA_NOT_EXIST);
        });
        List<SysDevice> service =deviceService.findByCId(cId);
        if(service.size()!=0 && category.getStatus()==1){
            category.setStatus(0);
            categoryMapper.updateCategory(category);
        }else {
            categoryMapper.deleteCategory(cId);
        }
        context.publishEvent(new CategoryChangeEvent());
    }

}
